//
//  CYWebScoket.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/9.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
@objc protocol DSWebSocketDelegate {
    /// 接收推送消息
    ///
    /// - Parameter data: 数据源
    @objc optional func archiveWebSocketInformation(data:ExchangeModel)
}

class ExchangeWebScoket: NSObject {
    //长连接请求配置
    var webScoketArr = [exchangeStyle.exchangeTick.rawValue,
                        exchangeStyle.exchangeDepth.rawValue,
                        exchangeStyle.exchangeChart.rawValue]
    ///线程队列
    lazy var  queue:OperationQueue =  {
       let quene = OperationQueue()
        quene.maxConcurrentOperationCount = 4
        return quene
    }()
    //webscoket
    var scoket:ExchangeScoket?
    
    //数据源
    var model:ExchangeModel?
    
    //代理
    var dataSource:DSWebSocketDelegate?
    //当前页面的webscoket种类
    var style:exchangeStyle?

    class func sharedInstance() -> ExchangeWebScoket
    {
        return manger
    }
    static let manger: ExchangeWebScoket  = {
        return ExchangeWebScoket()
    }()
    
    override init() {
        super.init()
        model = ExchangeModel()
    }
    
    
    /// 全局开启webscoket
    func creatScoket()  {
        let scoket = ExchangeScoket(model: model!)
        self.scoket = scoket
        scoket.delegate = self
        scoket.connectSever()
    }
    
    
    /// 添加webscoket 响应报文
    ///
    /// - Parameters:
    ///   - dataSource: 当前控制器
    ///   - style: 所属种类
    func creatScoket(dataSource:DSWebSocketDelegate?,style:exchangeStyle) {
        self.style = style
        let webInfor = ExchangeWebInfoFactory.manger.archiveWebInfor(identifier: style)
        if !webScoketArr.contains(style.rawValue) {
            webScoketArr.append(style.rawValue)
            if self.scoket?.scoket?.isConnected != nil {
                if (self.scoket?.scoket?.isConnected)! {
                    self.scoket?.sendWrite(infor: webInfor!, cancelBool: false)
                }
            }
        }
        
        if (webInfor as! CYWebInfoProtocol).oneceMovement {
            if (self.scoket?.checkScoketConnected())! {
                self.scoket?.sendWrite(infor: webInfor!, cancelBool: false)
            }
        }
        self.dataSource = dataSource
        self.style = style
    }

    //页面离开发送取消scoket报文
    func cancelSubscribe(dataSource:DSWebSocketDelegate?, style:exchangeStyle) {
        if webScoketArr.contains(style.rawValue) {
            let webInfor = ExchangeWebInfoFactory.manger.archiveWebInfor(identifier: style)
            if (self.scoket?.checkScoketConnected())! {
                self.scoket?.sendWrite(infor: webInfor!, cancelBool: true)
            }
            webScoketArr.ch_removeObject(style.rawValue)
        }
        if self.dataSource != nil {
            let period = self.dataSource as AnyObject
            let current = dataSource as AnyObject
            if period.isEqual(current) {
                self.dataSource = nil
            }

        }
    }
    
    //整合数据 上下游  K线数据
    func changeData(text: String) {
        let decompressedData = model!.gzip(data: text)
        if decompressedData == nil {
            return 
        }
        let dataStr : String = NSString(data: decompressedData!, encoding: String.Encoding.utf8.rawValue)! as String
        let dic:Dictionary? = model!.convertStringToDictionary(text: dataStr)!
        if dic == nil {return}
        let str:String = dic!["cmd"] != nil ? dic!["cmd"] as! String : "";
        let string:String = String(format: "exchange_%@", str)
        objc_sync_enter(self.model as Any)
        if (model?.OrganizeData(dic: dic!))! {
            if string == self.style?.rawValue {
                OperationQueue.main.addOperation {
                    if self.dataSource != nil && ((self.dataSource?.archiveWebSocketInformation) != nil) {
                        self.dataSource?.archiveWebSocketInformation!(data: self.model!)
                    }
                }
            }
        }
        objc_sync_exit(self.model as Any)
    }
}

extension ExchangeWebScoket:ExchangeScoketDelegate {

    func websocketDidConnect() {
        
        
    }
    
    func websocketDidDisconnect(error: NSError?) {
        
    }
    
    func websocketDidReceiveMessage(text: String) {
        let operation = BlockOperation {
            
            self.changeData(text: text)
        }
        self.queue.addOperation(operation)
        
    }
    
    func  websocketDidReceiveData(data: NSData) {
        
        
        
    }
    
    func exchangeScoketDidConnect() {
        for style in webScoketArr {
            let webInfor = ExchangeWebInfoFactory.manger.archiveWebInfor(identifier: exchangeStyle(rawValue: style)!)
            if (self.scoket?.checkScoketConnected())! {
                self.scoket?.sendWrite(infor: webInfor!, cancelBool: false)
                if style == exchangeStyle.exchangeChart.rawValue {
                    webScoketArr.ch_removeObject(style)
                }
            }
            
            if style == exchangeStyle.exchangeDepth.rawValue && self.dataSource == nil {
                if (self.scoket?.checkScoketConnected())! {
                    self.scoket?.sendWrite(infor: webInfor!, cancelBool: true)
                }
                webScoketArr.ch_removeObject(style)
            }
        }
        
    }

}
